package es.ikex.servlet;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import es.ikex.dao.ProductosDAO;

public class EditarProducto extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(request.getParameter("editar")!=null){
			boolean error = false;
			String codigo;
			String concepto;
			String descripcion;
			int codigoProveedores = 0;
			float precio = 0f;
			int stock = 0;
			int stockMinimo = 0 ;
			String fueraCatalogo;
			float alto = 0f;
			float ancho = 0f;
			float profundidad = 0f;
			
			codigo = request.getParameter("codigo");
			concepto = request.getParameter("concepto");
			descripcion = request.getParameter("descripcion");
			fueraCatalogo = request.getParameter("fueraCatalogo");
			
			if(concepto.equals("") || descripcion.equals("")){
				error = true;
				request.setAttribute("error", "Algun campo vacio");
			}
			try{
				codigoProveedores = Integer.parseInt(request.getParameter("proveedores"));
				stock = Integer.parseInt(request.getParameter("stock"));
				stockMinimo = Integer.parseInt(request.getParameter("stockMinimo"));
				alto = Float.parseFloat(request.getParameter("alto"));
				ancho = Float.parseFloat(request.getParameter("ancho"));
				profundidad = Float.parseFloat(request.getParameter("profundidad"));
				precio = Float.parseFloat(request.getParameter("precio"));
			}catch(NumberFormatException e){
				error = true;
				request.setAttribute("error", "Algun campo incorrecto");
			}
			if(!error){
				request.removeAttribute("error");
				ProductosDAO pro = new ProductosDAO();
				pro.editarProducto(codigo, concepto, descripcion, codigoProveedores, precio, stock, stockMinimo, fueraCatalogo, alto, ancho, profundidad);
			}
			else{
				request.getRequestDispatcher("Admin/edicionProducto.jsp").forward(request, response);
			}
		}
		else if(request.getParameter("editarCategoria")!=null){
			String codigo = "";
			String b = "";
			ProductosDAO pdt = new ProductosDAO();
			String codigoOld = request.getParameter("categoria") + request.getParameter("coleccion");
			String c = pdt.getCodigo(codigoOld);
			if(c != null && !c.equals("")){
				int a = Integer.parseInt(c.replaceAll(codigoOld, "0"));
				a++;
				b=a+"";
				while(b.length()!=3){
					b = "0" + b;
				}
			}
			else{
				b = "000";
			}
			codigo = codigoOld + b ; 
			codigoOld = request.getParameter("codigo");
			ProductosDAO pd = new ProductosDAO();
			pd.editarCategoria(codigoOld, codigo);
			
		}
		else{
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			Iterator<FileItem> iterator = null;
			String codigo = "";
			try {
				iterator = upload.parseRequest((RequestContext) request).iterator();
			} catch (FileUploadException e1) {
				e1.printStackTrace();
			}
			File uploadedFile;
			//String dirPath = "/Muebles/img/muebles";
			//String dirPath = "C:\\eclipse-jee-muebles\\WorkSpace\\Muebles\\WebContent\\img\\muebles";
			//String dirPath = "C:\\Tomcat7\\webapps\\Muebles\\img\\muebles";
			String dirPath = "/usr/local/tomcat/webapps/Muebles/img/muebles";
			while (iterator.hasNext()) {
				FileItem item = iterator.next();
				File fichero = new File(codigo + ".png");
				fichero.delete();
				if (!item.isFormField()) {
						String fileNameWithExt = codigo + ".png";

					File filePath = new File(dirPath);
						if (!filePath.exists()) {
						filePath.mkdirs();
					}
						uploadedFile = new File(dirPath + "/" + fileNameWithExt);
					try {
						item.write(uploadedFile);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else {
					if(item.getFieldName().equalsIgnoreCase("codigo"))
						codigo = item.getString();
				}
			}
			
		}
		
		request.getRequestDispatcher("Admin/modificacionOk.jsp").forward(request, response);
	}

}
